package com.rslai.commons.util;

import com.rslai.commons.util.exception.RunException;
import org.apache.ant.compress.taskdefs.Unzip;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;

import java.io.File;
import java.io.IOException;

/**
 * zip压缩解压缩工具类
 * Created by rslai on 2018/12/8.
 */
public class ZipUtil {

    /**
     * <p>解压缩zip文件</p>
     *
     * @param zipFileName zip文件名
     * @param destPath 目标目录
     */
    public void unZip(String zipFileName, String destPath) {
        FileUtil fileUtil = new FileUtil();
        if (!fileUtil.isFile(zipFileName)) {
            throw new RunException("zip压缩文件 “"+  zipFileName + "” 未找到！");
        }
        try {
            fileUtil.mkdirs(destPath);
        } catch (IOException e) {
        }
        if (!fileUtil.isDirectory(destPath)) {
            throw new RunException("目标目录创建失败 “"+  destPath + "” ");
        }

        Unzip unzipper = new Unzip();
        unzipper.setSrc(new File(zipFileName));
        unzipper.setDest(new File(destPath));
        unzipper.execute();
    }

    /**
     * <p>压缩文件</p>
     *
     * @param zipFileName zip文件名
     * @param srcPath 需要压缩的源目录
     */
    public void zip(String zipFileName, String srcPath) {
        File srcdir = new File(srcPath);
        if (!srcdir.exists()){
            throw new RunException("需要压缩的源目录 “"+  srcPath + "” 未找到！");
        }
        File zipFile = new File(zipFileName);
        if (zipFile.exists()){
            throw new RunException("zip文件名已存在 “"+  zipFileName);
        }

        Project prj = new Project();
        Zip zip = new Zip();
        zip.setProject(prj);
        zip.setDestFile(zipFile);
        FileSet fileSet = new FileSet();
        fileSet.setProject(prj);
        fileSet.setDir(srcdir);
        zip.addFileset(fileSet);
        zip.execute();
    }

}
